import { createStore } from "vuex";
import { TOKEN_KEY } from "@/api/params"

export type UserInfo  = {
  username: string,
}

const userInfo: UserInfo = {
  username: undefined,
}

export interface ReadRecord {
  id: string,
  name?: string,
  imgUrl?: string,
  chapterNum: number | string,
  updated: Date
}

export interface ShlefRecord {
  id: string,
  chapterNum: number | string
}

export const USER_INFO_SESSION_KEY = 'userInfo'
export const READ_RECORD_KEY = "localReadRecord"
export const SHELF_RECORD_KEY = "shelfRecord"

const store = createStore({
  state: {
    userInfo,
  },
  mutations: {
    setUserInfo: (state, userInfo: UserInfo) => {
      state.userInfo.username = userInfo.username;
      // window.sessionStorage.setItem(USER_INFO_SESSION_KEY, JSON.stringify(userInfo));
    },
    setUserInfoBySession: (state) => {
      // sesion中存在 用户信息
      if(window.sessionStorage.getItem(USER_INFO_SESSION_KEY)){
        // 放入 store
        state.userInfo = JSON.parse(window.sessionStorage.getItem(USER_INFO_SESSION_KEY))
      }
    },
    addUserInfoToSession: (state) => {
      // 用户名不为空
      if(state.userInfo.username){
        // 放入 session
        window.sessionStorage.setItem(USER_INFO_SESSION_KEY, JSON.stringify(state.userInfo));
      }
    },
    logout: (state) => {
      state.userInfo.username = undefined
      window.sessionStorage.removeItem(USER_INFO_SESSION_KEY);
    },
    setToken: (state, tokenResponse: string) => {
      localStorage.setItem(TOKEN_KEY, tokenResponse);
    },
    // 添加（更新）阅读记录
    // 这里 book的 name 与 imgUrl 可以没有是因为，会在目录界面点击连接时 添加一次，之后更新章节 都只需要 book id 更新 记录。
    addReadRecord: (state, payload: { book: {id: string, name?: string, imgUrl?: string}, chapterNum: string | number}) => {
      // 获取记录
      // console.log("clickIndex >", payload.chapterNum)
      let record: Array<ReadRecord> = store.getters.getReadRecord;
      // 如果 以及有记录，更新记录，变为 true
      let change = false;
      
      // 记录不为空
      if(record) {
        // 查询是否已经存在
        for(let i = 0; i < record.length ; i++) {
          // 存在
          if(record[i].id === payload.book.id) {
            // 更新日期
            record[i].updated = new Date();
            // 更新章节
            record[i].chapterNum = payload.chapterNum;
            // 删除，添加到最前边
            record.unshift(record.splice(i, 1)[0]);
            change = true
          }
        }
      }
      // 没有记录
      else {
        // 初始化
        record = []
      }

      // 之前不存在 ,记录数为 30
      if(!change) {
        if (record.length === 30) {
          // 删除最早的
          // record.shift();
          // 删除尾部，因为从头添加的
          record.pop()
        }
        // 有名字 与 图片链接
        if(payload.book.name && payload.book.imgUrl){
          let newRecord: ReadRecord = {
            id: payload.book.id,
            name: payload.book.name,
            imgUrl: payload.book.imgUrl,
            chapterNum: payload.chapterNum,
            updated: new Date()
          }
          // 添加在头部，为了顺序读取时 最先显示的是最近阅读记录
          record.unshift(newRecord);
        }
      }

      // 没记录 并且 给的信息不全，不添加
      localStorage.setItem(READ_RECORD_KEY, JSON.stringify(record))
    },
    removeShelfRecord: (state, payload: { bookId: string}) => {
      let shelfRecord = store.getters.getShelfRecord;
      if( shelfRecord ) {
        for(let i = 0; i < shelfRecord.length ; i++) {
          if(shelfRecord[i].id === payload.bookId) {
            //删除从指定位置deletePos开始的指定数量deleteCount的元素，数组形式返回所移除的元素
            shelfRecord.splice(i, 1);
            break;
          }
        }
        localStorage.setItem(SHELF_RECORD_KEY, JSON.stringify(shelfRecord));
      }
    },
    // 添加 阅读记录里 指定 书籍 id 的 信息到 书架 记录， 用于添加书架时使用
    addShelfRecordFromRead: (state, payload: { bookId: string} ) => {
      let readRecord = store.getters.getReadRecord
      // 从阅读记录找到 的 书籍 记录信息
      let bookRecord = undefined;
      // 从书架记录找到的 书籍 记录信息
      let shelfRecord = store.getters.getShelfRecord
      // 阅读记录不为空
      if(readRecord) {
        // 遍历 阅读记录
        for(let i = 0; i < readRecord.length ; i ++) {
          // 阅读记录里包含 书籍id 的 书籍信息
          if(readRecord[i].id === payload.bookId) {
            // 赋值, 这里 id 不变
            bookRecord = readRecord[i]
          }
        }
      }
      // 阅读记录里没有 或者为空，直接添加（移除书架时就把响应 LocalStorege 删除了，不会有）
      if(!bookRecord) {
        bookRecord.id = payload.bookId;
        bookRecord.chapterNum = 1;
      }
      if(!shelfRecord){
        shelfRecord = []
      }
      // 阅读记录里有
      // 添加进 书架记录
      shelfRecord.push({id: bookRecord.id, chapterNum: bookRecord.chapterNum})
      // 放入 LocalStorage
      localStorage.setItem(SHELF_RECORD_KEY, JSON.stringify(shelfRecord));
    },
    // 添加记录到书架
    addShelfRecord: (state, payload: { bookId: string, chapterNum: string | number}) => {
      // 获取记录
      let shelfRecord = store.getters.getShelfRecord;
      // 记录存在
      if ( shelfRecord ) {
        // 值是否被更改
        let change = false;
        // 遍历
        for (let i = 0 ; i < shelfRecord.length ; i ++) {
          // 记录已经存在
          if(shelfRecord[i].id === payload.bookId) {
            // 值更改
            shelfRecord[i].chapterNum = payload.chapterNum;
            change = true;
            break;
          }
        }
        // 值没有改
        if(!change) {
          // 添加
          shelfRecord.push({id: payload.bookId, chapterNum: payload.chapterNum});
        }
      }
      // 记录不存在
      else {
        // 初始化
        shelfRecord = []
        // 添加
        shelfRecord.push({id: payload.bookId, chapterNum: payload.chapterNum});
      }
      // 放入 LocalStorage
      localStorage.setItem(SHELF_RECORD_KEY, JSON.stringify(shelfRecord));
    }
  },
  getters: {
    getUserInfo: (state) => {
      return state.userInfo
    },
    getToken: (state) => {
      return localStorage.getItem(TOKEN_KEY);
    },
    getReadRecord: (state) => {
      let record = JSON.parse(localStorage.getItem(READ_RECORD_KEY));
      return record;
    },
    getShelfRecord: (state) => {
      // // shelfRecord 不仅获取书架的 LocalStorage ,还获取 阅读记录的 LocalStorage, 
      // // 主要是 开始只会阅读的时候放在阅读记录的 LocalStorage，进入书架时，获取 阅读记录的 LocalStorage
      // // XXXXXXXXXX 如果加入书架，应该两边都更新。
      // let shelfRecord = JSON.parse(localStorage.getItem(SHELF_RECORD_KEY));
      // if (!shelfRecord) {
      //   shelfRecord = []
      // }
      // let readRecord = store.getters.getReadRecord;
      // return shelfRecord.push(readRecord);
      return JSON.parse(localStorage.getItem(SHELF_RECORD_KEY));
    }
  }
})

export default store